export function arrayToTree(items: any[], key: string, pkey: string) {
  const res: any[] = []; // 存放结果集
  const map: any = {};
  // 判断对象是否有某个属性
  const getHasOwnProperty = (obj: any, property: any) =>
    Object.prototype.hasOwnProperty.call(obj, property);

  // 边做map存储，边找对应关系
  for (const i of items) {
    map[i[key]] = {
      ...i,
      children: getHasOwnProperty(map, i[key]) ? map[i[key]].children : [],
    };
    const newItem = map[i[key]];
    if (i[pkey] === 0) {
      res.push(newItem);
    } else {
      if (!getHasOwnProperty(map, i[pkey])) {
        map[i[pkey]] = {
          children: [],
        };
      }
      map[i[pkey]].children.push(newItem);
    }
  }
  return res;
}

export function treeToArray(tree: any[]) {
  const res: any[] = [];
  for (const i of tree) {
    res.push(i);
    if (i.children) {
      res.push(...treeToArray(i.children));
    }
  }
  return res;
}

// 删除树的无效children
export function dropTreeChildren(tree: any[]) {
  const treeList = tree.map((item: any): any => {
    if (item.children && item.children.length > 0) {
      return {
        ...item,
        children: dropTreeChildren(item.children),
      };
    } else {
      return {
        ...item,
        children: null,
      };
    }
  });
  return treeList;
}
